package org.mall.litemall.core.tasks.impl;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.mall.litemall.core.tasks.service.Task;
import org.mall.litemall.db.constant.CouponUserConstant;
import org.mall.litemall.db.domain.LitemallCouponUser;
import org.mall.litemall.db.service.LitemallCouponUserService;
import org.mall.litemall.core.service.ActionLogService;
import org.mall.litemall.core.utils.BeanUtil;

import java.util.Objects;

/**
 * 用户优惠券过期队列
 */
public class CouponUserExpiredTask extends Task {

    private final Log logger = LogFactory.getLog(CouponUserExpiredTask.class);
    private final Integer couponUserId;

    public CouponUserExpiredTask(Integer couponUserId, long delayInMilliseconds){
        super("CouponExpiredTask-" + couponUserId, delayInMilliseconds);
        this.couponUserId = couponUserId;
    }

    @Override
    public void run() {
        logger.info(String.format("系统处理延时任务 -> [开始-用户优惠券过期] [任务ID-%s]" , this.couponUserId));

        ActionLogService logService = BeanUtil.getBean(ActionLogService.class);
        LitemallCouponUserService couponUserService = BeanUtil.getBean(LitemallCouponUserService.class);

        LitemallCouponUser couponUser = couponUserService.findById(this.couponUserId);
        if(couponUser == null || !Objects.equals(CouponUserConstant.STATUS_USABLE , couponUser.getStatus())) return;

        couponUser.setStatus(CouponUserConstant.STATUS_EXPIRED);
        if (couponUserService.updateVersionSelective(couponUser) == 0) {
            throw new RuntimeException("用户优惠券过期设置失败");
        }

        logger.info(String.format("系统处理延时任务 -> [结束-用户优惠券过期] [任务ID-%s]" , this.couponUserId));
        logService.logOrderSucceed("系统处理延时任务",String.format("[结束-用户优惠券过期] [任务ID-%s]" , this.couponUserId));
    }
}
